package com.tanhua.server.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tanhua.common.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

/**
 * @author feihao
 * @version 1.0
 * @date 2021/6/29 20:25
 */

@Service
@Slf4j
public class UserService {

    @Autowired
    private RestTemplate restTemplate;

    @Value("${tanhua.sso.url}")
    private String ssoUrl;

    public User queryUserByToken(String token) {
        //校验token，返回user:
        String url = ssoUrl + "/user/" + token;
        try {
            //请求到sso系统的接口，校验token值。
            String data = restTemplate.getForObject(url, String.class);
            if (StringUtils.isEmpty(data)) {
                //token失效或者非法token
                return null;
            }
            return new ObjectMapper().readValue(data, User.class);
        } catch (Exception e) {
            log.error("校验token失败： token = " + token);
        }
        return null;
    }
}
